package com.yunduansing.demo.service.impl;

import com.yunduansing.demo.entity.MenuEntity;
import com.yunduansing.demo.mapper.MenuMapper;
import com.yunduansing.demo.model.menu.AntdMenuTreeModel;
import com.yunduansing.demo.model.menu.MenuTreeModel;
import com.yunduansing.demo.service.MenuService;
import com.yunduansing.demo.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统菜单表 服务实现类
 * </p>
 *
 * @author yunduansing
 * @since 2020-05-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {
    @Autowired
    private UserService userService;

    @Override
    public List<MenuTreeModel> getTree() {
        return generateTree(0, this.list());
    }

    private List<MenuTreeModel> generateTree(int pid, List<MenuEntity> entities) {
        var data = entities.stream().filter(x -> x.getPid() == pid).collect(Collectors.toList());
        var list = new ArrayList<MenuTreeModel>();
        if (data.size() > 0) {
            for (var item : data) {
                if (!item.getStatus()) {
                    var tree=new MenuTreeModel(item, generateTree(item.getId(), entities));
                    list.add(tree);
                }
            }
        }
        return list;
    }

    private List<AntdMenuTreeModel> generateAntdTree(int pid, List<MenuEntity> entities) {
        var data = entities.stream().filter(x -> x.getPid() == pid).collect(Collectors.toList());
        var list = new ArrayList<AntdMenuTreeModel>();
        if (data.size() > 0) {
            for (var item : data) {
                if (!item.getStatus()) {
                    list.add(new AntdMenuTreeModel(item.getId(),item.getUrl(),item.getIcon(), generateAntdTree(item.getId(), entities)));
                }
            }
        }
        return list;
    }

    @Override
    public List<AntdMenuTreeModel> getUserMenuTree(int userId,boolean admin) {
        if(admin){
            return generateAntdTree(0, this.list());
        }
        var user=userService.getById(userId);
        if(user.getIsAdmin()){
            return generateAntdTree(0, this.list());
        }
        return null;
    }

}
